/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vn.com.sml.SEFM.DAO;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.persistence.RollbackException;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.SystemException;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import vn.com.sml.SEFM.domain.Merchant;
import vn.com.sml.SEFM.domain.Ip;
import vn.com.sml.SEFM.domain.User;
import vn.com.sml.SEFM.domain.UserRoles;
import vn.com.sml.SEFM.domain.Userstatus;
import vn.com.sml.SEFM.util.HibernateUtil;


//import org.apache.log4j.Logger;

/**
 *
 * @author Tunp
 */
public class UserDAO {
    
    public static Integer saveUser(User user) throws SecurityException, RollbackException, HeuristicRollbackException, HeuristicMixedException, IllegalStateException, SystemException {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        Integer userId = null;
        try {
            transaction = (Transaction) session.beginTransaction();
            
            userId = (Integer) session.save(user);
            transaction.commit();
        }
        catch (HibernateException e){
            transaction.rollback();
            e.printStackTrace();
        }
        finally {
            session.close();
        }
        return userId;
    }
    
    public static List<User> listUsers() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        List<User> lst = new ArrayList<User>();
        try {
            transaction = (Transaction) session.beginTransaction();
            
            List lstUser = session.createQuery("from User").list();
            for (Iterator iterator = (Iterator) lstUser.iterator();iterator.hasNext();)
            {
                Userstatus usstatus;
                User user = (User) iterator.next();
                usstatus = (Userstatus) session.createQuery("select u.userstatus from User as u where u.userId="+user.getUserId()).uniqueResult();
                user.setUserstatus(usstatus);
                lst.add(user);
            }
            transaction.commit();
        }
        catch (HibernateException e){
            transaction.rollback();
            e.printStackTrace();
        }
        finally {
            session.close();
        }
        return lst;
    }
    
    public static User getUserById(int id)
    {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        User user = null;
        Merchant dvcnt = null;
        UserRoles usrole = null;
        Userstatus usstatus = null;
        try {
            transaction = (Transaction) session.beginTransaction();
            
            user = (User) session.createQuery("from User where user_id="+id).uniqueResult();
            dvcnt = (Merchant) session.createQuery("select u.merchant from User as u where u.userId="+id).uniqueResult();
            usrole = (UserRoles) session.createQuery("select u.userRoles from User as u where u.userId="+id).uniqueResult();
            usstatus = (Userstatus) session.createQuery("select u.userstatus from User as u where u.userId="+id).uniqueResult();
            
            user.setMerchant(dvcnt);
            user.setUserRoles(usrole);
            user.setUserstatus(usstatus);
            
            transaction.commit();
        }
        catch (HibernateException e){
            transaction.rollback();
            e.printStackTrace();
        }
        finally {
            session.close();
        }
        return user;
    }
    
    public static Boolean DeleteUser(int id)
    {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        Boolean flag = false;
        try {
            transaction = (Transaction) session.beginTransaction();
            Query query = session.createQuery("delete from User as u where userId="+id);
            int row = query.executeUpdate();
              if (row == 0){
                  System.out.println("Doesn't deleted any row!");
              }
              else{
                  System.out.println("DeletedRow: " + row);
              }
            flag = true;
            transaction.commit();
        }
        catch (HibernateException e){
            transaction.rollback();
            e.printStackTrace();
        }
        finally {
            session.close();
        }
        return flag;
    }
    
    public static Boolean update(User user) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        Boolean flag = false;
        try {
            transaction = (Transaction) session.beginTransaction();
            
            session.update(user);
            flag = true;
            transaction.commit();
        }
        catch (HibernateException e){
            transaction.rollback();
            e.printStackTrace();
        }
        finally {
            session.close();
        }
        return flag;
    }

    public static List<User> listUsers(String search_col, String search_text) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        List<User> lst = new ArrayList<User>();
        if(search_col.equals("Status")) {
            search_col = "userstatus.status";
        }
        else if(search_col.equals("Merchant")){
            search_col = "dvcnt.merchantName";
        }
        try {
            transaction = (Transaction) session.beginTransaction();
            
            List lstUser = session.createQuery("from User where " + search_col + " like '%" + search_text + "%'").list();
            for (Iterator iterator = (Iterator) lstUser.iterator();iterator.hasNext();)
            {
                Userstatus usstatus;
                User user = (User) iterator.next();
                usstatus = (Userstatus) session.createQuery("select u.userstatus from User as u where u.userId="+user.getUserId()).uniqueResult();
                user.setUserstatus(usstatus);
                lst.add(user);
            }
            transaction.commit();
        }
        catch (HibernateException e){
            transaction.rollback();
            e.printStackTrace();
        }
        finally {
            session.close();
        }
        return lst;
    }

    public static User LogIn(String username,String password) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        User user = new User();
        Merchant dvcnt = new Merchant();
        UserRoles usrole = new UserRoles();
        Userstatus usstatus = new Userstatus();
        try {
            transaction = (Transaction) session.beginTransaction();
            
            user = (User) session.createQuery("from User where userName='"+username+"'").uniqueResult();
            if(user != null) {
                dvcnt = (Merchant) session.createQuery("select u.merchant from User as u where userName='"+username+"'").uniqueResult();
                usrole = (UserRoles) session.createQuery("select u.userRoles from User as u where userName='"+username+"'").uniqueResult();
                usstatus = (Userstatus) session.createQuery("select u.userstatus from User as u where userName='"+username+"'").uniqueResult();

                user.setMerchant(dvcnt);
                user.setUserRoles(usrole);
                user.setUserstatus(usstatus);

                if(!user.getPassword().equals(password)){
                    user = new User();
                }
            }
            else
            {
                user = new User();
            }
            
            transaction.commit();
        }
        catch (HibernateException e){
            transaction.rollback();
            e.printStackTrace();
        }
        finally {
            session.close();
        }
        return user;
    }
}
